package com.gitee.wsl.common.commonmark.inline

import com.gitee.wsl.common.commonmark.lineMatch
import org.commonmark.internal.inline.InlineContentParser
import org.commonmark.internal.inline.InlineParserState
import org.commonmark.internal.inline.ParsedInline
import org.commonmark.internal.inline.Scanner
import org.commonmark.node.Node
import java.util.regex.Pattern

abstract class AbstractInlineParser<T: Node> : InlineContentParser,InlineNodeParser<T>{
    override fun tryParse(inlineParserState: InlineParserState): ParsedInline? {
        val scanner: Scanner = inlineParserState.scanner()
        val startPosition=scanner.position()
        if (scanner.find(specialCharacter()) > 0) {
            parse(scanner)?.let {
                return ParsedInline.of(it,startPosition)
            }
        }
        return ParsedInline.none()
    }
}


abstract class AbstractMatchInlineParser<T: Node> : AbstractInlineParser<T>() {

    override fun parse(scanner: Scanner): T? {
        scanner.lineMatch(getPattern())?.let {
            return createNode(it)
        }
        return null
    }

    abstract fun getPattern(): Pattern

    abstract fun createNode(text:String):T

}

interface InlineNodeParser<T: Node>{
    fun specialCharacter():Char
    fun parse(scanner: Scanner): T?
}